﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using P2.Cuberry.Framework.BOLBase;
using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Framework.Helper.Configuration;
using P2.Cuberry.Framework.Security;
using P2.Cuberry.Modules.Framework.ModuleManager.DAL;


namespace P2.Cuberry.Modules.Framework.ModuleManager.BusinessEntities
{
    public class XFieldValidation : BizObject, INotifyPropertyChanged
    {

        #region Constructors

        public XFieldValidation()
        {
            Modified = false;
        }

        public XFieldValidation(DAL.XConfigValidationFieldContent fieldValidation)
        {
            Load(fieldValidation);
            Modified = false;
        }

        #endregion


        #region Members

        int _validationId = 0;
        public int ValidationId
        {
            get { return _validationId; }
            set
            {
                if (value != _validationId)
                {
                    _validationId = value;
                    Modified = true;
                }
            }
        }

        string _moduleName = String.Empty;
        public string ModuleName
        {
            get { return _moduleName; }
            set
            {
                if (value != _moduleName)
                {
                    _moduleName = value;
                    Modified = true;
                }
            }
        }

        string _fieldEntityName = String.Empty;
        public string FieldEnitytName
        {
            get { return _fieldEntityName; }
            set
            {
                if (value != _fieldEntityName)
                {
                    _fieldEntityName = value;
                    Modified = true;
                }
            }
        }

        string _fieldName = String.Empty;
        public string FieldName
        {
            get { return _fieldName; }
            set
            {
                if (value != _fieldName)
                {
                    _fieldName = value;
                    Modified = true;
                }
            }
        }

        string _controlType = String.Empty;
        public string ControlType
        {
            get { return _controlType; }
            set
            {
                if (value != _controlType)
                {
                    _controlType = value;
                    Modified = true;
                }
            }
        }

        string _controlContentType = String.Empty;
        public string ControlContentType
        {
            get { return _controlContentType; }
            set
            {
                if (value != _controlContentType)
                {
                    _controlContentType = value;
                    Modified = true;
                }
            }
        }

        string _regEx = String.Empty;
        public string RegEx
        {
            get { return _regEx; }
            set
            {
                if (value != _regEx)
                {
                    _regEx = value;
                    Modified = true;
                }
            }
        }

        DateTime _minDateTime;
        public DateTime MinDateTime
        {
            get { return _minDateTime; }
            set
            {
                if (value != _minDateTime)
                {
                    _minDateTime = value;
                    Modified = true;
                }
            }
        }

        DateTime _maxDateTime;
        public DateTime MaxDateTime
        {
            get { return _maxDateTime; }
            set
            {
                if (value != _maxDateTime)
                {
                    _maxDateTime = value;
                    Modified = true;
                }
            }
        }

        int _minInt;
        public int MinInt
        {
            get { return _minInt; }
            set
            {
                if (value != _minInt)
                {
                    _minInt = value;
                    Modified = true;
                }
            }
        }

        int _maxInt;
        public int MaxInt
        {
            get { return _maxInt; }
            set
            {
                if (value != _maxInt)
                {
                    _maxInt = value;
                    Modified = true;
                }
            }
        }

        int _minText;
        public int MinText
        {
            get { return _minText; }
            set
            {
                if (value != _minText)
                {
                    _minText = value;
                    Modified = true;
                }
            }
        }

        int _maxText;
        public int MaxText
        {
            get { return _maxText; }
            set
            {
                if (value != _maxText)
                {
                    _maxText = value;
                    Modified = true;
                }
            }
        }

        string _validationType = String.Empty;
        public string ValidationType
        {
            get { return _validationType; }
            set
            {
                if (value != _validationType)
                {
                    _validationType = value;
                    Modified = true;
                }
            }
        }

        public Module ParentModule { set; get; }

        #endregion


        #region Read Operations

        public void Load(DAL.XConfigValidationFieldContent sourceEntity)
        {
            try
            {
                if (sourceEntity != null)
                {
                    this.ValidationId = sourceEntity.ValidationID;
                    this.ModuleName = sourceEntity.ModuleName;
                    this.FieldEnitytName = sourceEntity.EntityName;
                    this.FieldName = sourceEntity.FieldName;
                    this.ControlType = sourceEntity.ControlType;
                    this.ControlContentType = sourceEntity.ControlContentType;
                    this.RegEx = sourceEntity.RegEx;

                    if (sourceEntity.MinDateTime.HasValue)
                        this.MinDateTime = (DateTime)sourceEntity.MinDateTime;
                    
                    if (sourceEntity.MaxDateTime.HasValue)
                        this.MaxDateTime = (DateTime)sourceEntity.MaxDateTime;
                    
                    if (sourceEntity.MinInt.HasValue)
                        this.MinInt = (int)sourceEntity.MinInt;

                    if (sourceEntity.MaxInt.HasValue)
                        this.MaxInt = (int)sourceEntity.MaxInt;

                    if (sourceEntity.MinText.HasValue)
                        this.MinText = (int)sourceEntity.MinText;

                    if (sourceEntity.MaxText.HasValue)
                        this.MaxText = (int)sourceEntity.MaxText;
                    
                    this.ValidationType = sourceEntity.ValidationType;
                    
                    //Default Fields                
                    this.CreatedBy = sourceEntity.CreatedBy;
                    this.CreatedOn = sourceEntity.CreatedOn;
                    this.EditedBy = sourceEntity.EditedBy;
                    this.EditedOn = sourceEntity.EditedOn;
                    this.Timestamp = sourceEntity.TStamp;
                    //this.StatusID = sourceEntity.StatusID.GetValueOrDefault(P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID);
                    this.StatusID = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName).StatusID;
                }
                else
                {
                    this.ValidationId = 0;
                    this.ModuleName = string.Empty;
                    this.FieldEnitytName = string.Empty;
                    this.FieldName = string.Empty;
                    this.ControlType = string.Empty;
                    this.ControlContentType = string.Empty;
                    this.RegEx = string.Empty;
                    //this.MinDateTime = DateTime.MinValue;
                    //this.MaxDateTime = DateTime.MinValue;
                    this.MinInt = 0;
                    this.MaxInt = 0;
                    this.MinText = 0;
                    this.MaxText = 0;
                    this.ValidationType = string.Empty;

                    //Default Fields
                    this.CreatedBy = String.Empty;
                    this.EditedBy = String.Empty;
                    P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus initStatus = P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus.GetInitialStatus(this.EntityName);
                    this.StatusID = initStatus.StatusID;
                }
                Modified = false;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        public static ObservableCollection<XFieldValidation> GetxFieldValidationFor(Module xMod, PropertyChangedEventHandler onChange)
        {
            try
            {
                ObservableCollection<XFieldValidation> itemsCollection = new ObservableCollection<XFieldValidation>();

                string connectionString = ConfigurationSetUp.GetEntConnectionString("Business", Properties.Settings.Default.EntityResources);
                using (ModuleManagerDataContext db = new ModuleManagerDataContext(connectionString))
                {
                    var xFieldContents = from tranItem in db.XConfigValidationFieldContent
                                        where tranItem.ModuleName == xMod.ModuleName
                                        select tranItem;
                    if (xFieldContents.Count() > 0)
                    {
                        foreach (var fieldContent in xFieldContents)
                        {
                            itemsCollection.Add(new XFieldValidation(fieldContent) { ParentModule = xMod });
                        }
                    }
                }

                return itemsCollection;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", "XAppResources", System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        #endregion


        #region Update Operations

        public P2MessageStack InsertAndUpdate(ModuleManagerDataContext db)
        {
            P2MessageStack MessageStack = new P2MessageStack();

            try
            {
                if (string.IsNullOrEmpty(this.CreatedBy)) 
                    this.CreatedBy = User.Current.UserID;
                
                this.EditedBy = User.Current.UserID;
                
                DAL.XConfigValidationFieldContent editedItem;
                //if (this.ResourceName != String.Empty)
                if (this.ValidationId == 0)
                {
                    editedItem = new DAL.XConfigValidationFieldContent()
                    {
                        ModuleName = this.ModuleName,
                        EntityName = this.FieldEnitytName,
                        FieldName = this.FieldName,
                        ControlType = this.ControlType,
                        ControlContentType = this.ControlContentType,
                        RegEx = this.RegEx,
                        MinInt = this.MinInt,
                        MaxInt = this.MaxInt,
                        MinText = this.MinText,
                        MaxText = this.MaxText,
                        ValidationType = this.ValidationType,
                        
                        //Default Fields
                        CreatedBy = User.Current.UserID,
                        CreatedOn = DateTime.Now,
                        EditedBy = User.Current.UserID,
                        EditedOn = DateTime.Now,
                        //StatusID = this.StatusID
                    };

                    if (this.MinDateTime == DateTime.MinValue)
                        editedItem.MinDateTime = null;
                    else
                        editedItem.MinDateTime = this.MinDateTime;

                    if (this.MaxDateTime == DateTime.MinValue)
                        editedItem.MaxDateTime = null;
                    else
                        editedItem.MaxDateTime = this.MaxDateTime;

                    db.AddToXConfigValidationFieldContent(editedItem);
                }
                else
                {
                    editedItem = (from ti in db.XConfigValidationFieldContent
                                  where ti.ValidationID == this.ValidationId
                                  select ti).First();
                    if (editedItem.TStamp == this.Timestamp)
                    {
                        editedItem.ModuleName = this.ModuleName;
                        editedItem.EntityName = this.FieldEnitytName;
                        editedItem.FieldName = this.FieldName;
                        editedItem.ControlType = this.ControlType;
                        editedItem.ControlContentType = this.ControlContentType;
                        editedItem.RegEx = this.RegEx;

                        if (this.MinDateTime == DateTime.MinValue)
                            editedItem.MinDateTime = null;
                        else
                            editedItem.MinDateTime = this.MinDateTime;

                        if (this.MaxDateTime == DateTime.MinValue)
                            editedItem.MaxDateTime = null;
                        else
                            editedItem.MaxDateTime = this.MaxDateTime;

                        editedItem.MinInt = this.MinInt;
                        editedItem.MaxInt = this.MaxInt;
                        editedItem.MinText = this.MinText;
                        editedItem.MaxText = this.MaxText;
                        editedItem.ValidationType = this.ValidationType;
                                                
                        //Default Fields
                        editedItem.EditedBy = User.Current.UserID;
                        editedItem.EditedOn = DateTime.Now;
                        //editedItem.StatusID = this.StatusID;

                        //track changes!
                        //this.SaveChangeLog(-multiple Fields-);
                    }
                    else
                    {
                        MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("TMsg_PaymentNotUpdated")));
                    }
                }
            }
            catch (Exception ex) //AM:TC!!
            {
                MessageStack.Add(new P2TransactionMessage("red", P2Translator.GetResource("Error_Error")));
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
            return MessageStack;
        }

        public void Delete(ModuleManagerDataContext db)
        {
            if (this.ValidationId != 0)
            {
                var item = (from ti in db.XConfigValidationFieldContent
                            where this.ValidationId == ti.ValidationID
                            select ti).First();
                db.DeleteObject(item);
                db.SaveChanges();
            }
        }

        #endregion


        #region Validation
        //Empty
        #endregion


        #region Copy Operations

        public XFieldValidation GetCopy()
        {
            try
            {
                XFieldValidation newItem = new XFieldValidation();
                newItem.ParentModule = this.ParentModule;
                newItem.ValidationId = this.ValidationId;

                newItem.ModuleName = this.ModuleName;
                newItem.FieldEnitytName = this.FieldEnitytName;
                newItem.FieldName = this.FieldName;
                newItem.ControlType = this.ControlType;
                newItem.ControlContentType = this.ControlContentType;
                newItem.RegEx = this.RegEx;
                newItem.MinDateTime = this.MinDateTime;
                newItem.MaxDateTime = this.MaxDateTime;
                newItem.MinInt = this.MinInt;
                newItem.MaxInt = this.MaxInt;
                newItem.MinText = this.MinText;
                newItem.MaxText = this.MaxText;
                newItem.ValidationType = this.ValidationType;

                newItem.Timestamp = this.Timestamp;
                newItem.Modified = this.Modified;
                return newItem;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
                return null;
            }
        }

        public void UpdateFrom(XFieldValidation sourceItem)
        {
            try
            {
                this.ParentModule = sourceItem.ParentModule;
                this.ModuleName = sourceItem.ModuleName;

                this.FieldEnitytName = sourceItem.FieldEnitytName;
                this.FieldName = sourceItem.FieldName;
                this.ControlType = sourceItem.ControlType;
                this.ControlContentType = sourceItem.ControlContentType;
                this.RegEx = sourceItem.RegEx;
                this.MinDateTime = sourceItem.MinDateTime;
                this.MaxDateTime = sourceItem.MaxDateTime;
                this.MinInt = sourceItem.MinInt;
                this.MaxInt = sourceItem.MaxInt;
                this.MinText = sourceItem.MinText;
                this.MaxText = sourceItem.MaxText;
                this.ValidationType = sourceItem.ValidationType;

                this.Timestamp = sourceItem.Timestamp;
                this.Modified = sourceItem.Modified;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }

        #endregion


        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        public void OnAllPropertiesChanged()
        {
            OnPropertyChanged("ValidationId");
            OnPropertyChanged("ModuleName");
            OnPropertyChanged("FieldEnitytName");
            OnPropertyChanged("FieldName");
            OnPropertyChanged("ControlType");
            OnPropertyChanged("ControlContentType");
            OnPropertyChanged("RegEx");
            OnPropertyChanged("MinDateTime");
            OnPropertyChanged("MaxDateTime");
            OnPropertyChanged("MinInt");
            OnPropertyChanged("MaxInt");
            OnPropertyChanged("MinText");
            OnPropertyChanged("MaxText");
            OnPropertyChanged("ValidationType");
        }

        #endregion


        #region Validator

        public override P2Validator Validator
        {
            get
            {
                if (_validator == null)
                {
                    _validator = new P2Validator(Properties.Settings.Default.ModuleName, this.EntityName, "ResourceName", this);
                }
                return _validator;
            }
        }

        #endregion
    }
}
